package org.example.onlinejudge.controller;

import org.example.onlinejudge.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 管理员权限管理控制器
 */
@Controller
@RequestMapping("/admin/permissions")
@PreAuthorize("hasRole('0')") // 仅管理员可访问
public class AdminPermissionController {

    @Autowired
    private PermissionService permissionService;

    /**
     * 权限列表页面
     */
    @GetMapping
    // @PreAuthorize("hasAuthority('permission:view')") // 临时注释掉，用于调试
    public String permissionList(Model model) {
        System.out.println("\n========== 访问权限管理页面 ==========");
        
        var permissions = permissionService.findAllPermissions();
        
        System.out.println("✓ 查询到权限数量: " + permissions.size());
        
        model.addAttribute("permissions", permissions);
        
        System.out.println("✓ 返回模板: admin/permissions");
        System.out.println("========== 处理完成 ==========\n");
        
        return "admin/permissions";
    }

    /**
     * 添加权限
     */
    @PostMapping("/add")
    @PreAuthorize("hasAuthority('permission:add')")
    public String addPermission(@RequestParam("permCode") String permCode,
                               @RequestParam("permName") String permName,
                               RedirectAttributes redirectAttributes) {
        try {
            permissionService.createPermission(permCode, permName);
            redirectAttributes.addFlashAttribute("success", "权限添加成功");
            return "redirect:/admin/permissions";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "添加失败：" + e.getMessage());
            return "redirect:/admin/permissions";
        }
    }

    /**
     * 编辑权限
     */
    @PostMapping("/edit/{id}")
    @PreAuthorize("hasAuthority('permission:edit')")
    public String editPermission(@PathVariable Long id,
                                @RequestParam("permCode") String permCode,
                                @RequestParam("permName") String permName,
                                RedirectAttributes redirectAttributes) {
        try {
            permissionService.updatePermission(id, permCode, permName);
            redirectAttributes.addFlashAttribute("success", "权限更新成功");
            return "redirect:/admin/permissions";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "更新失败：" + e.getMessage());
            return "redirect:/admin/permissions";
        }
    }

    /**
     * 删除权限
     */
    @PostMapping("/delete/{id}")
    @PreAuthorize("hasAuthority('permission:delete')")
    public String deletePermission(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        try {
            permissionService.deletePermission(id);
            redirectAttributes.addFlashAttribute("success", "权限删除成功");
            return "redirect:/admin/permissions";
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "删除失败：" + e.getMessage());
            return "redirect:/admin/permissions";
        }
    }
}
